package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryDto;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitDyo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gqs
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
    implements RoomInfoService {
  @Autowired private ApartmentInfoMapper apartmentInfoMapper;
  @Autowired private GraphInfoMapper graphInfoMapper;
  @Autowired private RoomInfoMapper roomInfoMapper;
  @Autowired private RoomAttrValueMapper roomAttrValueMapper;
  @Autowired private RoomFacilityMapper roomFacilityMapper;
  @Autowired private RoomLabelMapper roomLabelMapper;
  @Autowired private RoomPaymentTypeMapper roomPaymentTypeMapper;
  @Autowired private RoomLeaseTermMapper roomLeaseTermMapper;

  @Autowired private GraphInfoService graphInfoService;
  @Autowired private RoomAttrValueService roomAttrValueService;
  @Autowired private RoomFacilityService roomFacilityService;
  @Autowired private RoomLabelService roomLabelService;
  @Autowired private RoomPaymentTypeService roomPaymentTypeService;
  @Autowired private RoomLeaseTermService roomLeaseTermService;
  @Autowired private FileService fileService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean saveOrUpdateRoom(RoomSubmitDyo roomSubmitDyo) {
    // 1.房间信息添加唯一性校验
    Long id = roomSubmitDyo.getId() == null ? -1L : roomSubmitDyo.getId();
    // 同一个公寓下面的房间号不能重复
    RoomInfo roomInfo =
        this.getOne(
            Wrappers.lambdaQuery(RoomInfo.class)
                .eq(RoomInfo::getApartmentId, roomSubmitDyo.getApartmentId())
                .eq(RoomInfo::getRoomNumber, roomSubmitDyo.getRoomNumber())
                .last("limit 1"));
    if (roomInfo != null && !roomInfo.getId().equals(id)) {
      throw new StgyException(ResultCodeEnum.ROOM_INFO_EXISTS_ERROR);
    }
    // 2.根据id判断是添加还是修改
    // 修改数据前 先删除原先的映射数据
    if (id != -1L) {
      // 删除原有graphInfoList
      graphInfoMapper.deleteGraphInfoById(id);
      // 删除原有roomAttrValueList
      roomAttrValueMapper.deleteAttrValueById(id);
      // 删除原有roomFacilityList
      roomFacilityMapper.deleteFacilityById(id);
      // 删除原有roomLabelList
      roomLabelMapper.deleteLabelById(id);
      // 删除原有paymentTypeList
      roomPaymentTypeMapper.deletePaymentTypeById(id);
      // 删除原有leaseTermList
      roomLeaseTermMapper.deleteLeaseTermById(id);
    }
    // 3.保存数据
    this.saveOrUpdate(roomSubmitDyo);
    // 保存新的graphInfoList
    List<GraphVo> graphVoList = roomSubmitDyo.getGraphVoList();
    if (!CollectionUtils.isEmpty(graphVoList)) {
      ArrayList<GraphInfo> graphInfoList = new ArrayList<>();
      for (GraphVo graphVo : graphVoList) {
        GraphInfo graphInfo = new GraphInfo();
        // graphInfo.setId(null); // 采用逻辑删除 主键值可能会重复
        graphInfo.setItemType(ItemType.ROOM);
        graphInfo.setItemId(roomSubmitDyo.getId());
        graphInfo.setName(graphVo.getName());
        graphInfo.setUrl(graphVo.getUrl());
        graphInfoList.add(graphInfo);
      }
      graphInfoService.saveBatch(graphInfoList);
    }
    // 保存新的roomAttrValueList
    List<Long> attrValueIds = roomSubmitDyo.getAttrValueIds();
    if (!CollectionUtils.isEmpty(attrValueIds)) {
      List<RoomAttrValue> roomAttrValueList = new ArrayList<>();
      for (Long attrValueId : attrValueIds) {
        RoomAttrValue roomAttrValue =
            RoomAttrValue.builder().roomId(roomSubmitDyo.getId()).attrValueId(attrValueId).build();
        roomAttrValueList.add(roomAttrValue);
      }
      roomAttrValueService.saveBatch(roomAttrValueList);
    }
    // 3.保存新的facilityInfoList
    List<Long> facilityInfoIds = roomSubmitDyo.getFacilityInfoIds();
    if (!CollectionUtils.isEmpty(facilityInfoIds)) {
      List<RoomFacility> roomFacilityList = new ArrayList<>();
      for (Long facilityInfoId : facilityInfoIds) {
        RoomFacility roomFacility =
            RoomFacility.builder().roomId(roomSubmitDyo.getId()).facilityId(facilityInfoId).build();
        roomFacilityList.add(roomFacility);
      }
      roomFacilityService.saveBatch(roomFacilityList);
    }

    // 4.保存新的labelInfoList
    List<Long> labelInfoIds = roomSubmitDyo.getLabelInfoIds();
    if (!CollectionUtils.isEmpty(labelInfoIds)) {
      ArrayList<RoomLabel> roomLabelList = new ArrayList<>();
      for (Long labelInfoId : labelInfoIds) {
        RoomLabel roomLabel =
            RoomLabel.builder().roomId(roomSubmitDyo.getId()).labelId(labelInfoId).build();
        roomLabelList.add(roomLabel);
      }
      roomLabelService.saveBatch(roomLabelList);
    }

    // 5.保存新的paymentTypeList
    List<Long> paymentTypeIds = roomSubmitDyo.getPaymentTypeIds();
    if (!CollectionUtils.isEmpty(paymentTypeIds)) {
      ArrayList<RoomPaymentType> roomPaymentTypeList = new ArrayList<>();
      for (Long paymentTypeId : paymentTypeIds) {
        RoomPaymentType roomPaymentType =
            RoomPaymentType.builder()
                .roomId(roomSubmitDyo.getId())
                .paymentTypeId(paymentTypeId)
                .build();
        roomPaymentTypeList.add(roomPaymentType);
      }
      roomPaymentTypeService.saveBatch(roomPaymentTypeList);
    }

    // 6.保存新的leaseTermList
    List<Long> leaseTermIds = roomSubmitDyo.getLeaseTermIds();
    if (!CollectionUtils.isEmpty(leaseTermIds)) {
      ArrayList<RoomLeaseTerm> roomLeaseTerms = new ArrayList<>();
      for (Long leaseTermId : leaseTermIds) {
        RoomLeaseTerm roomLeaseTerm =
            RoomLeaseTerm.builder().roomId(roomSubmitDyo.getId()).leaseTermId(leaseTermId).build();
        roomLeaseTerms.add(roomLeaseTerm);
      }
      roomLeaseTermService.saveBatch(roomLeaseTerms);
    }
    return true;
  }

  @Override
  public IPage<RoomItemVo> pageItem(IPage<RoomItemVo> page, RoomQueryDto queryVo) {
    return roomInfoMapper.pageRoomItemQuery(page, queryVo);
  }

  @Override
  public RoomDetailVo getRoomDetailById(Long id) {
    // 1.查询RoomInfo
    RoomInfo roomInfo = roomInfoMapper.selectById(id);
    // 2.查询room所属公寓信息
    ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(roomInfo.getApartmentId());
    // 3.查询room的图片信息
    List<GraphVo> graphVoList = graphInfoMapper.selectGraphVoListByItemTypeAndId(ItemType.ROOM, id);
    // 4.查询room的attrValue信息
    List<AttrValueVo> attrValueVoList = roomAttrValueMapper.selectAttrValueVoListByRoomId(id);
    // 5.查询room的facility信息
    List<FacilityInfo> facilityInfoList = roomFacilityMapper.selectFacilityInfoListByRoomId(id);
    // 6.查询room的label信息
    List<LabelInfo> labelInfoList = roomLabelMapper.selectLabelInfoListByRoomId(id);
    // 7.查询room的paymentType信息
    List<PaymentType> paymentTypeList = roomPaymentTypeMapper.selectPaymentTypeListByRoomId(id);
    // 8.查询room的leaseTerm信息
    List<LeaseTerm> leaseTermList = roomLeaseTermMapper.selectLeaseTermListByRoomId(id);

    RoomDetailVo adminRoomDetailVo = new RoomDetailVo();
    BeanUtils.copyProperties(roomInfo, adminRoomDetailVo);

    adminRoomDetailVo.setApartmentInfo(apartmentInfo);
    adminRoomDetailVo.setGraphVoList(graphVoList);
    adminRoomDetailVo.setAttrValueVoList(attrValueVoList);
    adminRoomDetailVo.setFacilityInfoList(facilityInfoList);
    adminRoomDetailVo.setLabelInfoList(labelInfoList);
    adminRoomDetailVo.setPaymentTypeList(paymentTypeList);
    adminRoomDetailVo.setLeaseTermList(leaseTermList);

    return adminRoomDetailVo;
  }

  @Override
  public boolean removeRoomById(Long id) {
    // 1.删除roomInfo
    this.removeById(id);
    // 2.删除graphInfoList
    graphInfoService.remove(
        Wrappers.lambdaQuery(GraphInfo.class)
            .eq(GraphInfo::getItemId, id)
            .eq(GraphInfo::getItemType, ItemType.ROOM));
    // 删除minio中的房间图片
    List<GraphInfo> UrlList =
        graphInfoMapper.selectList(
            Wrappers.lambdaQuery(GraphInfo.class)
                .eq(GraphInfo::getItemType, ItemType.ROOM)
                .eq(GraphInfo::getItemId, id));
    for (GraphInfo graphInfo : UrlList) {
      fileService.delete(graphInfo.getUrl());
    }
    // 3.删除AttrValueList
    roomAttrValueService.remove(
        Wrappers.lambdaQuery(RoomAttrValue.class).eq(RoomAttrValue::getRoomId, id));
    // 4.删除facilityInfoList
    roomFacilityService.remove(
        Wrappers.lambdaQuery(RoomFacility.class).eq(RoomFacility::getRoomId, id));
    // 5.删除labelInfoList
    roomLabelService.remove(Wrappers.lambdaQuery(RoomLabel.class).eq(RoomLabel::getRoomId, id));
    // 6.删除paymentTypeList
    roomPaymentTypeService.remove(
        Wrappers.lambdaQuery(RoomPaymentType.class).eq(RoomPaymentType::getRoomId, id));
    // 7.删除leaseTermList
    roomLeaseTermService.remove(
        Wrappers.lambdaQuery(RoomLeaseTerm.class).eq(RoomLeaseTerm::getRoomId, id));
    return true;
  }
}
